package com.ruoyi.system.controller;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.row.SimpleRowHeightStyleStrategy;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.temple.DetailTemple;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 明细Controller
 *
 * @author xuliang
 * @date 2024-03-29
 */
@RestController
@RequestMapping("/system/detail")
@Slf4j
public class ProcurementDetailController extends BaseController
{
    @Autowired
    private IProjectInfoService projectInfoService;
    @Autowired
    private IProcurementDetailService procurementDetailService;
    @Autowired
    private ILaborService laborService;
    @Autowired
    private IDirectService directService;
    @Autowired
    private IIndirectService indirectService;
    @Autowired
    private IOutputService outputService;
    @Autowired
    protected Validator validator;

    /**
     * 查询明细列表
     */
    @PreAuthorize("@ss.hasPermi('system:detail:list')")
    @GetMapping("/list")
    public Map<String,Object> list(ProcurementDetail procurementDetail)
    {

        if(!RoleUtils.hasPermission(projectInfoService.getRoleIdsByUserId(getUserId()))){
            procurementDetail.setProjectCode(projectInfoService.getProjectCodeByUserId(getUserId()));
        }else {
            procurementDetail.setProjectCode(null);
        }

        startPage();

        List<ProcurementDetail> detailList = procurementDetailService.selectProcurementDetailList(procurementDetail);

        List<String> projectCodeList = projectInfoService.getProjectCodes(procurementDetail.getAreaId());

        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("projectCodeList",projectCodeList);
        dataMap.put("dataList",getDataTable(detailList));

        Map<Integer,Map<Integer,Object>> map = new HashMap<>();

        return dataMap;
    }


    /**
     * 获取明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:detail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(procurementDetailService.selectProcurementDetailById(id));
    }

    /**
     * 新增明细
     */
    @PreAuthorize("@ss.hasPermi('system:detail:add')")
    @Log(title = "明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProcurementDetail procurementDetail)
    {

        procurementDetail.calculateTax();
        procurementDetail.setProjectCode(projectInfoService.getProjectCodeByUserId(getUserId()));
        procurementDetail.setCreateBy(getUsername());
        procurementDetail.setCreateTime(DateUtils.getNowDate());

        procurementDetail.setDateNumber(DateUtils.getMonth());
        projectInfoService.updateProjectNumber(DateUtils.getMonth(),procurementDetail.getProjectCode());

        return toAjax(procurementDetailService.insertProcurementDetail(procurementDetail));
    }

    /**
     * 修改明细
     */
    @PreAuthorize("@ss.hasPermi('system:detail:edit')")
    @Log(title = "明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProcurementDetail procurementDetail)
    {

        procurementDetail.calculateTax();
        procurementDetail.setUpdateBy(getUsername());
        procurementDetail.setUpdateTime(DateUtils.getNowDate());

        return toAjax(procurementDetailService.updateProcurementDetail(procurementDetail));
    }

    /**
     * 删除明细
     */
    @PreAuthorize("@ss.hasPermi('system:detail:remove')")
    @Log(title = "明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(procurementDetailService.deleteProcurementDetailByIds(ids));
    }


    @Log(title = "材料采购明细导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:detail:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,
                                 @RequestParam("areaId")String areaStr,
                                 @RequestParam("dateNumber")String dateNumber) throws Exception
    {
        log.info("areaId: " + areaStr);
        Integer areaId = Integer.parseInt(areaStr);

        ExcelUtil<ProcurementDetail> util = new ExcelUtil<ProcurementDetail>(ProcurementDetail.class);
        if(file.isEmpty()){
            return error("文件为空");
        }

        InputStream inputStream = file.getInputStream();

        List<ProcurementDetail> detailList = util.importExcel(inputStream,2);

        if (StringUtils.isNull(detailList) || detailList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }

        LocalDate currentDate = LocalDate.now();
        int currentYear = currentDate.getYear();
        int currentMonth = currentDate.getMonthValue();
        String operName = getUsername();

        //
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        int count;
        for (ProcurementDetail detail : detailList)
        {
            detail.setAreaId(areaId);
            detail.setProjectCode(projectInfoService.getProjectCodeByUserId(getUserId()));
            if(detail.getDateNumber() != null){
                String entityDate = detail.getDateNumber();
                LocalDate entityLocalDate = LocalDate.parse(entityDate + "-01");

                int entityYear = entityLocalDate.getYear();
                int entityMonth = entityLocalDate.getMonthValue();
                if(currentYear == entityYear && currentMonth == entityMonth){
                    detail.setDateNumber(DateUtils.getMonth());
                }
            }else {
                detail.setDateNumber(dateNumber);
                log.info("前端 dateNumber：" + dateNumber);
            }
            try
            {
                // 验证是否存在该条数据
                ProcurementDetail query = new ProcurementDetail();
                query.setProjectCode(detail.getProjectCode());
                query.setContractCode(detail.getContractCode());
                query.setDateNumber(detail.getDateNumber());
                query.setSupplier(detail.getSupplier());

                count = procurementDetailService.countDetailByContractCodeAndNumber(query);

                BeanValidators.validateWithException(validator, detail);
                if(count != 0){
                    detail.setUpdateBy(operName);
                    detail.setUpdateTime(DateUtils.getNowDate());
                    detail.calculateTax();
                    procurementDetailService.updateProcurementDetail(detail);
                    successNum++;
                    successMsg.append("<br/>").append(successNum)
                            .append("、明细 ：").append(detail.getItemName())
                            .append(" ， 合同编号 ：").append(detail.getContractCode())
                            .append(" 更新成功");
                }else {
                    detail.setCreateBy(operName);
                    detail.setCreateTime(DateUtils.getNowDate());
                    detail.calculateTax();
                    procurementDetailService.insertProcurementDetail(detail);
                    successNum++;
                    successMsg.append("<br/>").append(successNum)
                            .append("、明细 ：").append(detail.getItemName())
                            .append(" ， 合同编号 ：").append(detail.getContractCode())
                            .append(" 导入成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、明细 ：" + detail.getItemName() + (" ， 合同编号 ：") + detail.getContractCode()
                        + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "部分导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        inputStream.close();

        return success(successMsg.toString());
    }

    /*
     * @author : xuliang
     * @date   : 2024/4/15
     * @description : 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {

        // 创建 ExcelWriter 对象
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).relativeHeadRowIndex(2).build();

        // 设置表头样式
        WriteCellStyle headCellStyle = new WriteCellStyle();
        WriteFont headFont = new WriteFont();
        headFont.setFontHeightInPoints((short) 10); // 设置字体大小
        headCellStyle.setWriteFont(headFont);
        headCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 设置背景颜色
        headCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        //垂直居中,水平居中
        headCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headCellStyle.setBorderLeft(BorderStyle.THIN);
        headCellStyle.setBorderTop(BorderStyle.THIN);
        headCellStyle.setBorderRight(BorderStyle.THIN);
        headCellStyle.setBorderBottom(BorderStyle.THIN);
        headCellStyle.setWrapped(true);

        // 创建自定义的内容样式
        WriteCellStyle contentCellStyle = new WriteCellStyle();
        WriteFont contentFont = new WriteFont();
        contentFont.setFontHeightInPoints((short) 10); // 设置字体大小
        contentCellStyle.setWriteFont(contentFont);
        contentCellStyle.setWrapped(true); // 设置文字过长时自动换行
        //垂直居中,水平居中
        contentCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentCellStyle.setBorderLeft(BorderStyle.THIN);
        contentCellStyle.setBorderTop(BorderStyle.THIN);
        contentCellStyle.setBorderRight(BorderStyle.THIN);
        contentCellStyle.setBorderBottom(BorderStyle.THIN);

        // 创建 模板 Excel
        WriteSheet detailTemplate = EasyExcel.writerSheet(0,"材料采购明细")
                .head(DetailTemple.class)
                .registerWriteHandler(new SheetHandler())
                .registerWriteHandler(new HorizontalCellStyleStrategy(headCellStyle,contentCellStyle))
                .registerWriteHandler(new SimpleRowHeightStyleStrategy((short)40,(short)20)) // 简单的行高策略：头行高30，内容行高20
                .build();

        // 创建 模板 数据对象
        List<DetailTemple> detailTemplateDataList = new ArrayList<>();
        detailTemplateDataList.add(new DetailTemple());

        excelWriter.write(detailTemplateDataList, detailTemplate);

        excelWriter.finish();
    }


    /**
     * 导出明细列表
     */
    @PreAuthorize("@ss.hasPermi('system:detail:export')")
    @Log(title = "明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProcurementDetail procurementDetail)
    {
        List<ProcurementDetail> list = procurementDetailService.selectProcurementDetailList(procurementDetail);
        ExcelUtil<ProcurementDetail> util = new ExcelUtil<ProcurementDetail>(ProcurementDetail.class);
        util.exportExcel(response, list, "明细数据");
    }

}
